package chapter23.h23_1.exe;

import chapter23.h23_1.language.Executor;
import chapter23.h23_1.language.ExecutorFactory;

public class StringFactoryIml implements ExecutorFactory {
    final private static int GO = 1;
    final private static int TURN_RIGHT = 2;
    final private static int TURN_LEFT = 3;
    private Executor executor;

    public void setExecutor(Executor executor){
        this.executor = executor;
    }

    public void turnTo(int direction){
        switch (direction){
            case TURN_RIGHT:
                System.out.println(" <right> ");
                break;
            case TURN_LEFT:
                System.out.println(" <left> ");
                break;
        }
    }

    public void go(int action){
        switch (action){
            case GO:
                System.out.println(" <go> ");
        }
    }

    @Override
    public Executor createExecutor(String name) {
        switch (name){
            case "go":
                return new GoExecutor(this,GO);
            case "right":
                return new DirectionExecutor(this,TURN_RIGHT);
            case "left":
                return new DirectionExecutor(this,TURN_LEFT);
            default:
                System.err.println("unvalued command: "+name);
        }
        return null;
    }



    abstract class StringExecutor implements Executor {
        protected StringFactoryIml stringFactoryIml;
        public StringExecutor(StringFactoryIml stringFactoryIml){
            this.stringFactoryIml = stringFactoryIml;
        }
        public abstract void execute();
    }



    class GoExecutor extends StringExecutor{
        private int action;
        public GoExecutor (StringFactoryIml stringFactoryIml, int action){
            super(stringFactoryIml);
            this.action = action;
        }

        @Override
        public void execute() {
            stringFactoryIml.go(action);
        }
    }

    class DirectionExecutor extends StringExecutor{
        private int direction;
        public DirectionExecutor(StringFactoryIml stringFactoryIml, int direction) {
            super(stringFactoryIml);
            this.direction = direction;
        }

        @Override
        public void execute() {
            stringFactoryIml.turnTo(direction);
        }
    }
}
